<?php
namespace app\index\controller;

use think\Request;
use app\index\model\User;
use think\facade\Session;

class Login extends Base
{
    public function index()
    {
        // 跳转到注册页面
        $this->redirect('login/create');
    }

    public function create()
    {
        return $this->fetch('create');
    }

    public function save(Request $request)
    {
        if(!$request->isAjax()){
            $this->redirect('login/create');
        }else if(!$request->isPost()){
            $this->error('访问页面不存在');
        }

        $mobile = $request->post('mobile');
        $password = $request->post('password');
        $userModel = new User();
        $login_result = $userModel->login($mobile, $password);
        if($login_result->status){
            $remember = $request->post('remember');
            if($remember){
                Session::init(['expire' => 0]);
            }
            $login_data = $login_result->data;
            // current_user是Object，不是数组
            Session::set("current_user", $login_data['user']);
            $this->success($login_result->message, url('root'), $login_result->data);
        }else{
            $this->error($login_result->message);
        }
    }

    public function delete(Request $request)
    {
        if($request->isPost()){
            Session::delete("current_user");
        }
        $this->redirect('root');
    }
}
